<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use App\Models\Role;
use App\Models\AdminWallet;

class CreateUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:user {name} {phone} {password} {role}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '通过命令创建一个管理员用户';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $name = $this->argument('name');
        $phone = $this->argument('phone');
        $password = $this->argument('password');
        $roleCode = $this->argument('role');
        Log::info("创建用户{$name},{$phone},{$password},{$roleCode}");
        $role = Role::whereCode($roleCode)->first();
        if(!$role){
            Log::error('角色'.$roleCode.'不存在');
            return 0;
        }
        $user = User::wherePhone($phone)->first();
        if($user){
            Log::error('用户'.$phone.'已存在!');
            return 0;
        }
        // 查询
        $user = new User();
        $user->name = $name;
        $user->phone = $phone;
        $user->role_code = $roleCode;
        $user->password = bcrypt($password);
        $user->save();
        AdminWallet::create(['user_id'=>$user->id]);
        Log::info("创建用户成功{$name},{$phone},{$password},{$roleCode}");
    }
}
